﻿using System;
using System.Collections.Generic;
using System.Windows.Controls;
using Microsoft.Phone.Controls;
using unifiqAnthony.UnifiqSvc;
using Microsoft.Phone.Controls.Maps;
using System.Collections.ObjectModel;
using System.Text;
using unifiqAnthony.Class;
using System.Device.Location;

namespace unifiqAnthony
{
    public partial class ListingMap : PhoneApplicationPage
    {
        ByteToImageConverter c = new ByteToImageConverter();
        //List<Listing> listListing = null;
        MapLayer uniLayer = new MapLayer();
        MapLayer listingLayer = new MapLayer();
        List<Listing> listingList = null;
        List<University> uniList = null;
        int uid;
        UnifiqSvc.ServiceSoapClient svc = new UnifiqSvc.ServiceSoapClient();

        public ListingMap()
        {
            InitializeComponent();

            var obj = App.Current as App;
            uid = obj.uid;

            // Get Uni's | STEP 1
            svc.getAllUniCompleted += new EventHandler<getAllUniCompletedEventArgs>(svc_getAllUniCompleted);
            svc.getAllUniAsync();
            tb_loading.Text = "Loading Listings";
            progressOverlay.Show();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

        }

        void svc_getAllUniCompleted(object sender, UnifiqSvc.getAllUniCompletedEventArgs e)
        {
            // Get Listings | STEP 2
            uniList = new List<University>(e.Result);
            svc.getAvailListingCompleted += new EventHandler<getAvailListingCompletedEventArgs>(svc_getAvailListingCompleted);
            svc.getAvailListingAsync(uid);

            showAllUni();
        }

        void showAllUni()
        {
            ObservableCollection<SampleData> dataSource = new
            ObservableCollection<SampleData>();
            foreach (University u in uniList)
            {
                object temp = null;

                if (u.uniName == "NUS")
                    temp = this.Resources["nusPin"] as ControlTemplate;
                else if (u.uniName == "NTU")
                    temp = this.Resources["ntuPin"] as ControlTemplate;
                else if (u.uniName == "SMU")
                    temp = this.Resources["smuPin"] as ControlTemplate;
                else if (u.uniName == "SIT")
                    temp = this.Resources["sitPin"] as ControlTemplate;

                dataSource.Add(new SampleData()
                {
                        template = temp,
                        loc = new GeoCoordinate(u.lat, u.lon),
                });
            }

            this.UniControl.ItemsSource = dataSource; 
        }

        void svc_getAvailListingCompleted(object sender, UnifiqSvc.getAvailListingCompletedEventArgs e)
        {
            listingList = new List<Listing>(e.Result);
            progressOverlay.Hide();
            // Populate Map with all Listings | STEP 3

            showAllListing();
        }

        void showAllListing()
        {
            ObservableCollection<SampleData> dataSource = new
            ObservableCollection<SampleData>();
            foreach (Listing l in listingList)
            {
                StringBuilder builder = new StringBuilder();
                builder.Append("Blk " + l.blkNo + " " + l.stName + " St. " + l.stNo + "\n");
                builder.Append("$" + l.fee + " / Tenant \n");
                builder.Append(l.noOfTenants + " Tenant(s)");

                dataSource.Add(new SampleData()
                {   
                    bmp = c.ConvertByteArrayToBitMapImage(l.img1),
                    text = builder.ToString(),
                    loc = new GeoCoordinate(l.lat, l.lon),
                    listing = l,
                    //template = this.Resources["listingPin"] as ControlTemplate
                });
            }

            this.ListingControl.ItemsSource = dataSource; 

            /*
            Pushpin pin = new Pushpin();
            GeoCoordinate geo = new GeoCoordinate(l.lat, l.lon);

            Map.ZoomLevel = 17;
            Map.Center = geo;
            */

        }

        //method to calculate distance between current location and each supermarket
        public List<Listing> GetDistanceBetweenPoints(University uni, List<Listing> listingList)
        {
            foreach (Listing l in listingList)
            {
                double lat2 = l.lat;
                double long2 = l.lon;
                double distance = 0;
                double dLat = (lat2 - uni.lat) / 180 * Math.PI;
                double dLong = (long2 - uni.lon) / 180 * Math.PI;
                double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2)
                + Math.Cos(lat2) * Math.Sin(dLong / 2) * Math.Sin(dLong / 2);
                double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
                //Calculate radius of earth
                // assume any of the two points.
                double radiusE = 6378135; // Equatorial radius, in metres
                double radiusP = 6356750; // Polar Radius
                //Numerator part of function
                double nr = Math.Pow(radiusE * radiusP * Math.Cos(uni.lat / 180 * Math.PI), 2);
                //Denominator part of the function
                double dr = Math.Pow(radiusE * Math.Cos(uni.lat / 180 * Math.PI), 2)
                + Math.Pow(radiusP * Math.Sin(uni.lat / 180 * Math.PI), 2);
                double radius = Math.Sqrt(nr / dr);
                //Calaculate distance in metres.
                distance = radius * c;
                
                if (uni.uniName == "NUS")
                {
                    l.distFromNUS = distance;
                }
                else if (uni.uniName == "NTU")
                {
                    l.distFromNTU = distance;
                }
                else if (uni.uniName == "SMU")
                {
                    l.distFromSMU = distance;
                }
                else if (uni.uniName == "SIT")
                {
                    l.distFromSIT = distance;
                }
            }
            return listingList;
        }

        private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("Button_Click");
        }

        void pushPin_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("Pushpin tapped");

            Type t = sender.GetType();
            System.Diagnostics.Debug.WriteLine(t.ToString());

            var p = (Pushpin)sender;

            var g = (Border)p.FindName("border");
            if (g.Visibility == System.Windows.Visibility.Collapsed)
                g.Visibility = System.Windows.Visibility.Visible;
            else
                g.Visibility = System.Windows.Visibility.Collapsed;

            e.Handled = true;

        }

        private void Pushpin_Hold(object sender, System.Windows.Input.GestureEventArgs e)
        {

            //Get the data object that represents the current selected item
            Listing l = (sender as Pushpin).Tag as Listing;

            // Set selected Listing to obj.listing
            var obj = App.Current as App;
            obj.listing = l;

            List<byte[]> byteList = new List<byte[]>();
            byteList.Add(null); byteList.Add(null); byteList.Add(null); // Create 3 slots

            if (l.img1 != null)
                byteList[0] = l.img1;
            if (l.img2 != null)
                byteList[1] = l.img2;
            if (l.img3 != null)
                byteList[2] = l.img3;

            obj.byteList = byteList;
            NavigationService.Navigate(new Uri("/ListingView.xaml", UriKind.Relative));
        }

        
    }
}